/**
 * 
 */
package org.demetra.jets.bdb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

import org.demetra.jets.TupleSet;
import org.demetra.jets.TupleStoreException;

import com.ericsson.otp.erlang.OtpErlangTuple;
import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.Environment;
import com.sleepycat.db.EnvironmentConfig;

/**
 * @author vjache
 *
 */
public class TupleStore {

	private static boolean create = true;
	private Environment _env;

	/**
	 * @throws FileNotFoundException 
	 * 
	 */
	public TupleStore() throws FileNotFoundException {
		System.setErr(new PrintStream(new FileOutputStream("./ZZZ.log"),true));
		System.err.println("Init tuple store...");

		try {

			EnvironmentConfig envConfig = new EnvironmentConfig();
			envConfig.setInitializeCache(true);
			envConfig.setCacheSize(400000000);
//			envConfig.setInitializeLocking(true);
			if (create) {
				envConfig.setAllowCreate(true);
			}
			_env = new Environment(new File("."), envConfig);

			System.err.println("Tuple store initialized.");
		} catch (DatabaseException e) {
			e.printStackTrace();
			throw new TupleStoreException(e);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new TupleStoreException(e);
		} catch (Exception e) {
			e.printStackTrace();
			throw new TupleStoreException(e);
		}
	}
	
	public TupleSet<OtpErlangTuple> openTupleSet(String aName)
	{
		try {
			return new BdbOtpTupleSet(_env,aName);
		} catch (Exception e) {
			e.printStackTrace();
			throw new TupleStoreException(e);
		}
	}
	
	public void close()
	{
		try {
			_env.close();
		} catch (DatabaseException e) {
			e.printStackTrace();
			throw new TupleStoreException(e);
		}
	}

}
